package graphic.dialogs;

import graphic.MainFrame;
import graphic.ToolBar;
import graphic.mycomponents.TextChecked;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import utility.GraphicUtilsFactory;
import core.Configuration;
import core.Server;
import dbms.DBCheckAndConfigurationFunctions;

public class ServerConfigurationDialog extends AbstractDialog 
{
	TextChecked userId;
	TextChecked password;
	
	TextChecked mainPath;
	TextChecked tempDir;
	TextChecked connectionPort;
	TextChecked fileTransferPort;

	boolean isFirstConfiguration;
	
	public ServerConfigurationDialog()
	{	
		super("First Configuration", "Configure", 300, 420, false);
		
		this.isFirstConfiguration = !DBCheckAndConfigurationFunctions.isConfigTableSet();
		
		super.construct();
	}
	
	@Override
	public void createPanel() 
	{
		super.setPanel(new JPanel(new GridBagLayout()));		
		JPanel panel = super.getPanel(); 
		
		this.createFields();
		
		GridBagConstraints c = new GridBagConstraints();
		c.insets = new Insets(5, 10, 5, 10);
		c.fill = GridBagConstraints.BOTH;
		c.anchor = GridBagConstraints.CENTER;
		
		c.gridx = 0;
		c.gridy = 0;
		c.gridwidth = 2;
		panel.add(new JLabel("Server First Configuration"), c);
		
		c.gridx = 0;
		c.gridy = 1;
		panel.add(this.userId, c);	
	
		c.gridx = 0;
		c.gridy = 2;
		panel.add(this.password, c);
		
		c.gridx = 0;
		c.gridy = 3;
		panel.add(this.mainPath, c);
		
		c.gridx = 0;
		c.gridy = 4;
		panel.add(this.tempDir, c);
		
		c.gridx = 0;
		c.gridy = 5;
		panel.add(this.connectionPort, c);
		
		c.gridx = 0;
		c.gridy = 6;
		panel.add(this.fileTransferPort, c);
		
		c.gridx = 0;
		c.gridy = 7;
		c.gridwidth = 1;
		panel.add(super.getOkButton(), c);	
	
		c.gridx = 1;
		c.gridy = 7;
		panel.add(super.getExitButton(), c);	
	}

	public void createFields()
	{
		HashMap<Integer, String> configs = Server.getInstance().getConfigs();
		if(configs == null) configs = new HashMap<Integer, String>();
		
		this.userId = new TextChecked(configs.get(0), TextChecked.TEXT, true, false, null);
		this.password = new TextChecked(configs.get(1), TextChecked.PASSWORD, true, false, null);
		
		if(this.isFirstConfiguration)
		{
			this.mainPath = new TextChecked("", TextChecked.WRITABLE_FOLDER, true, false, null);
			this.tempDir = new TextChecked("temp", TextChecked.TEXT, true, false, null);
			
			this.connectionPort = new TextChecked("7000", TextChecked.INT, true, false, null);
			this.fileTransferPort = new TextChecked("8000", TextChecked.INT, true, false, null);
		} else {
			this.mainPath = new TextChecked(configs.get(2), TextChecked.WRITABLE_FOLDER, false, false, null);
			this.tempDir = new TextChecked(configs.get(5), TextChecked.TEXT, false, false, null);
			
			this.connectionPort = new TextChecked(configs.get(3), TextChecked.INT, true, false, null);
			this.fileTransferPort = new TextChecked(configs.get(4), TextChecked.INT, true, false, null);
		}
		
		GraphicUtilsFactory.setTitleAndBorderToComponent(this.userId, "User Name");
		GraphicUtilsFactory.setTitleAndBorderToComponent(this.password, "Password");
		GraphicUtilsFactory.setTitleAndBorderToComponent(this.mainPath, "Server Main Path");
		GraphicUtilsFactory.setTitleAndBorderToComponent(this.tempDir, "Server Temp Dir");
		GraphicUtilsFactory.setTitleAndBorderToComponent(this.connectionPort, "Server Connection Port");
		GraphicUtilsFactory.setTitleAndBorderToComponent(this.fileTransferPort, "Server File Transfer Port");
	}

	@Override
	public boolean checkOkFunction()
	{
		// TODO: BISOGNA CONTROLLARE CHE LA CARTELLA MAIN DIR E LA CARTELLA TEMP SIANO INSERITE E SCRIVIBILI 
		
		if(!this.userId.isChecked() || !this.password.isChecked() ||!this.tempDir.isChecked() ||
				!this.connectionPort.isChecked() || !this.fileTransferPort.isChecked())
		{
			JOptionPane.showMessageDialog(this, "Please check you have filled correctly all fields!", "Error configuring the server!", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		
		if(this.connectionPort.getText().equals(this.fileTransferPort.getText()))
		{
			JOptionPane.showMessageDialog(this, "Connection and FileTransfer port must be not equal!", "Error configuring the server!", JOptionPane.ERROR_MESSAGE);
			return false;			
		}
		
		return true;
	}

	@Override
	public void okFunction()
	{
		if(!this.isFirstConfiguration)
		{
			if(JOptionPane.showConfirmDialog(this, "Per effettuare correttamente tutte le modifiche è necessario " +
					 "riavviare il server.\n Ciò significa che tutti i processi in corsi, quali chat e committing di files saranno interrotti!\n" +
					 "Sei sicuro di voler continuare?", "Server Restart", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION)
				return;
			
			try { Server.getInstance().stopServer(); } catch (IOException e) {}
			
			if(Configuration.setServerUser(this.userId.getText(), this.password.getText())
					&& Configuration.setServerConnectionPort(Integer.parseInt(this.connectionPort.getText()))
					&& Configuration.setFileTransferConfigurationPort(Integer.parseInt(this.fileTransferPort.getText())))
				MainFrame.getInstance().showMessage("Server Configured!", JOptionPane.INFORMATION_MESSAGE);
			else
				MainFrame.getInstance().showMessage("Server NOT Configured!", JOptionPane.ERROR_MESSAGE);			

			Server.getInstance().startServer();
			
			super.dispose();
			return;
		}
		
		if(Configuration.createDB()
				&& Configuration.setServerUser(this.userId.getText(), this.password.getText())
				&& Configuration.setServerMainPath(this.mainPath.getText())
				&& Configuration.setServerTempDir(this.tempDir.getText())
				&& Configuration.setServerConnectionPort(Integer.parseInt(this.connectionPort.getText()))
				&& Configuration.setFileTransferConfigurationPort(Integer.parseInt(this.fileTransferPort.getText())))
		{
			super.dispose();
			MainFrame.getInstance().showMessage("Server Configured!", JOptionPane.INFORMATION_MESSAGE);
			ToolBar.getInstance().disableAllButtonsInsteadOf(ToolBar.ONLY_RUN);
		}
		else
			MainFrame.getInstance().showMessage("Server NOT Configured!", JOptionPane.ERROR_MESSAGE);		
	}
	
	@Override
	public void exitFunction()
	{
		if(!Configuration.isConfigured())
		{
			MainFrame.getInstance().showMessage("Server must be configured to be used!", JOptionPane.WARNING_MESSAGE);
			super.dispose();
			
			MainFrame.getInstance().dispose();
		} else
			super.dispose();
	}
}